package com.hs.task.quartz;


import com.hs.task.po.DongMaiPo;
import com.hs.task.po.FormPo;
import com.hs.task.util.HttpRequestUtils;
import com.hs.task.util.JaxbUtil;
import com.hs.task.util.JsonDateValueProcessor;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by chenyq5 on 2016-6-1.
 */
@Controller
@RequestMapping("/dongMai")
@Component("dongMaiTask")
public class DongMaiTask {

    @Value("${uploadDMUrl}")
    private String uploadURL;
    @RequestMapping("upload")
    @ResponseBody
    //  @Scheduled(cron="0 * * * * *")
    public Map<String, Object> execute() {
        Map<String,Object> result =new HashMap<String, Object>();
        try {
            result = uploadDongMaiData();
        } catch (Exception e) {
            result.put("status",-2);
            result.put("msg",e.getMessage());
            e.printStackTrace();
        }
            return result;


    }

    public Map<String, Object> uploadDongMaiData()  {
      /*  DongMaiProModel proModel = DongMaiProModel.dongMaiProDao.findById(1);
        String rootDir=proModel.getStr("rootDir");*/
        Map<String,Object> resultMap=new HashMap<String, Object>();
        int mark=1;
        String msg="操作成功";
        List<String> failedList = new ArrayList<String>();
        String rootDir = "d://dongmai/";
        Date today = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String todayStr = format.format(today);
        String todyaDirStr = rootDir + todayStr + "/";
        File todayDir = new File(todyaDirStr);
        File[] files = todayDir.listFiles();
        if (files == null) {
            mark=0;
            msg="不存在以今天为日期命名的文件夹";
        }else {
            for (File f : files) {
                if (f.getName().endsWith(".xml")) {
                    try {
                        int i = processXml(f.getAbsolutePath());
                        if(i==1){
                            f.renameTo(new File(f.getAbsolutePath() + "_processed"));
                        }
                    }catch (IOException e){
                        mark=-1;
                        msg="存在处理失败的文件";
                        failedList.add(f.getAbsolutePath());
                        e.printStackTrace();
                    } catch (DocumentException e) {
                        mark=-1;
                        msg="存在处理失败的文件";
                        e.printStackTrace();
                        failedList.add(f.getAbsolutePath());
                    }catch (NullPointerException e){
                        mark=-1;
                        msg="存在处理失败的文件";
                        e.printStackTrace();
                        failedList.add(f.getAbsolutePath());
                    }
                }
            }
        }
         resultMap.put("mark",mark);
        resultMap.put("msg",msg);
        resultMap.put("fieldList",failedList);
        return resultMap;
    }

    public int processXml(String filePath) throws DocumentException, IOException {
        FormPo form = JaxbUtil.converyToJavaBean(filePath, FormPo.class);
        DongMaiPo po = form.getDongMaiPo();
        int result;
            double rbpulseP = po.getRbSYS().doubleValue() - po.getRbDIA().doubleValue();
            double lbpulseP = po.getLbSYS().doubleValue() - po.getLbDIA().doubleValue();
            double rapulseP = po.getRaSYS().doubleValue() - po.getRaDIA().doubleValue();
            double lapulseP = po.getLaSYS().doubleValue() - po.getLaDIA().doubleValue();
            po.setRbpulseP(BigDecimal.valueOf(rbpulseP));
            po.setLbpulseP(BigDecimal.valueOf(lbpulseP));
            po.setRapulseP(BigDecimal.valueOf(rapulseP));
            po.setLapulseP(BigDecimal.valueOf(lapulseP));
            po.setInsert_time(new Date());
            // po.setSync_time(null);
            //  String url = "http://localhost:8082/impl/hessian/test/saveOrUpdate";
            JsonConfig jsConfig = new JsonConfig();
            jsConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
            jsConfig.registerJsonValueProcessor(Integer.class, new JsonDateValueProcessor());
            JSONObject jsonObject = JSONObject.fromObject(po, jsConfig);

            JSONObject jsonObject1 = null;

            jsonObject1 = HttpRequestUtils.httpPost(uploadURL, jsonObject);
            result = jsonObject1.getInt("mark");

        return result;
    }

/*    public boolean processXml(String filePath) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File(filePath));
        Element root = document.getRootElement();
        Iterator rootIt = root.elementIterator();
        DongMaiPo po = new DongMaiPo();
        while (rootIt.hasNext()) {
            Element element = (Element) rootIt.next();
            Iterator elemIt = element.elementIterator();
            while (elemIt.hasNext()) {
                Element item = (Element) elemIt.next();
                po.set(item.getName(), item.getData());
            }
            double rbpulseP = (Double.parseDouble(po.getStr("RbSYS")) - Double.parseDouble(po.getStr("RbDIA")));
            double lbpulseP = (Double.parseDouble(po.getStr("LbSYS")) - Double.parseDouble(po.getStr("LbDIA")));
            double rapulseP = (Double.parseDouble(po.getStr("RaSYS")) - Double.parseDouble(po.getStr("RaDIA")));
            double lapulseP = (Double.parseDouble(po.getStr("LaSYS")) - Double.parseDouble(po.getStr("LaDIA")));
            po.set("RbpulseP", rbpulseP);
            po.set("LbpulseP", lbpulseP);
            po.set("RapulseP", rapulseP);
            po.set("LapulseP", lapulseP);
            po.set("insert_time", new Date());
            po.save();
        }
        return true;
    }*/
}
